package com.day0;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author leonard
 * @Description
 * @date 2021-05-21 15:56
 */
public class NettyServer {
    public static void main(String[] args) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //boss对应IOServer.java中的接受连接线程，主要负责创建连接
        NioEventLoopGroup boss = new NioEventLoopGroup();
        //worker对应IOServer.java中的负责读取数据的线程，主要用于读取数据以及业务逻辑处理
        NioEventLoopGroup worker = new NioEventLoopGroup();
        serverBootstrap
                .group(boss, worker)//1.设置线程模型
                .channel(NioServerSocketChannel.class)//2.设置IO模型为nio
                .childHandler(new ChannelInitializer<NioSocketChannel>() {//3.连接并读写处理逻辑,IO处理逻辑
                    //ChannelInitializer 对每条数据进行业务处理
                    protected void initChannel(NioSocketChannel ch) {
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                System.out.println(msg);
                            }
                        });
                    }
                })
                .bind(8000);
    }
}
